import {Component, ChangeDetectorRef} from '@angular/core'
import {PhotoLibrary} from '@ionic-native/photo-library'

@Component({
  selector: 'page-native-photo-library',
  templateUrl: 'photo-library.html'
})
export class NativePhotoLibraryPage {

  library: any = []
  times: number = 0
  disabled: boolean = false

  constructor(
    private photoLibrary: PhotoLibrary,
    private cd: ChangeDetectorRef
  ) {
    this.getPhotoLibrary = this.getPhotoLibrary.bind(this)
  }

  getPhotoLibrary() {
    let watch = null
    let self = this
    this.photoLibrary.requestAuthorization().then(() => {
      this.times = 0
      this.disabled = true
      watch = this.photoLibrary.getLibrary({
        quality: 10,
        itemsInChunk: 10,
        chunkTimeSec: 10,
        useOriginalFileNames: false,
        includeAlbumData: false
      }).subscribe({
        next: library => {
          this.times++
          //手动触发视图更新
          this.library = this.library.concat(library)
          this.cd.detectChanges()
          if (this.times == 10) {
            //获取太多容易死机
            actionDone()
            this.cd.detectChanges()
          }
        },
        error: err => {
          actionDone()
          this.cd.detectChanges()
        },
        complete: () => {
          actionDone()
          this.cd.detectChanges()
        }
      });
    }).catch(err => console.log('permissions weren\'t granted'));

    function actionDone() {
      self.disabled = false
      watch.unsubscribe()
    }
  }

}
